package org.yunai.swjg.server.module.item.container;

import org.yunai.swjg.server.module.item.template.ItemTemplate;
import org.yunai.swjg.server.module.item.vo.Item;
import org.yunai.swjg.server.module.player.vo.Player;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 道具背包/仓库背包
 * User: yunai
 * Date: 13-4-6
 * Time: 下午4:55
 */
public class ShoulderBag extends CommonBag {

    private final Player player;

    public ShoulderBag(Player player, BagType bagType, int capacity) {
        super(player, bagType, capacity);
        this.player = player;
    }

    public List<Item> addItem(ItemTemplate template, int count) {
        // 校验是否能放下
        if (count == 0 || getMaxCanAdd(template) < count) {
            return Collections.emptyList();
        }

//        try {
//            do {
//                // 记录道具产生日志
//                genKey = KeyUtil.UUIDKey();
//                Globals.getLogService().sendItemGenLog(player, reason, detailReason,
//                        template.getId(), template.getName(), count, bind.index, 0, "", genKey);
//                // 增加物品增加原因到reasonDetail
//                String countChangeReason = " [genReason:" + reason.getClass()
//                        .getField(reason.name()).getAnnotation(ReasonDesc.class).value()
//                        + "] ";
//                detailReason = detailReason == null ? countChangeReason
//                        : detailReason + countChangeReason;
//            } while (false);
//        } catch (Exception e) {
        // TODO 等以后有日志服务器在加
//            LoggerFactory.itemLogger.error(LogUtils.buildLogInfoStr(player.getUUID(),
//                    "记录向包中添加一定数量物品日志时出错"), e);
//        }
        List<Item> updateItems = new ArrayList<>(count / template.getMaxOverlap() + 1);
        int left = count;
        // 在可以叠加的情况下，优先叠加
        if (template.canOverlap()) {
            left = addToOverlapSlot(template, left, updateItems);
        }
        // 放到空格位置
        if (left > 0) {
            left = addToEmptySlot(template, left, updateItems);
        }
        if (left != 0) {
            // TODO LOG下
        }
        return updateItems;
    }

    public List<Item> removeItem(ItemTemplate template, final int count) {
        // 检查道具是否足够
        if (count == 0 || getCountByTemplateId(template.getId()) < count) {
            return new ArrayList<>(0);
        }
        // 按叠加个数进行升序排序
        List<Item> items = super.getByTemplateId(template.getId());
        Collections.sort(items, Item.COMPARATOR_OVERLAP);
        // 扣除道具
        List<Item> changedItems = new ArrayList<>(count / template.getMaxOverlap() + 1);
        int left = count;
        for (Item item : items) {
            if (left >= item.getOverlap()) {
                left -= item.getOverlap();
                item.changeOverlap(0);
            } else {
                item.changeOverlap(item.getOverlap() - left);
                left = 0;
            }
            changedItems.add(item);
            if (left == 0) {
                break;
            }
        }
        return changedItems;
    }

    /**
     * 向可叠加位置添加道具(不考虑空格)，一直放，并返回剩余的个数
     *
     * @param template    道具模版
     * @param count       添加数量
     * @param updateItems 更新的道具列表
     * @return 剩余的个数
     */
    private int addToOverlapSlot(ItemTemplate template, final int count, List<Item> updateItems) {
        if (count == 0) {
            return 0;
        }
        int left = count;
        for (Item item : items) {
            if (left == 0) {
                break;
            }
            if (Item.isEmpty(item) || !ItemTemplate.isEqual(item.getTemplate(), template)) {
                continue;
            }
            if (item.getOverlap() < item.getMaxOverlap()) {
                int capacity = template.getMaxOverlap() - item.getOverlap();
                if (capacity >= left) {
                    item.changeOverlap(item.getOverlap() + left);
                    left = 0;
                } else {
                    item.changeOverlap(template.getMaxOverlap());
                    left -= capacity;
                }
                updateItems.add(item);
            }
        }
        return left;
    }

    /**
     * 向空位添加道具，一直放，并返回剩余的个数
     *
     * @param template    道具模版
     * @param count       添加数量
     * @param updateItems 更新的道具列表
     * @return 剩余的个数
     */
    private int addToEmptySlot(ItemTemplate template, final int count, List<Item> updateItems) {
        if (count == 0) {
            return 0;
        }
        int left = count;
        int bagIndex = -1;
        for (Item item : items) {
            bagIndex++;
            if (left == 0) {
                break;
            }
            if (item != null) {
                continue;
            }

            Item newItem;
            if (left <= template.getMaxOverlap()) {
                newItem = Item.save(player, Item.OWNER_ID_NONE, template, getBagType(), bagIndex, left);
                left = 0;
            } else {
                newItem = Item.save(player, Item.OWNER_ID_NONE, template, getBagType(), bagIndex, template.getMaxOverlap());
                left -= template.getMaxOverlap();
            }
            updateItems.add(newItem);
        }
        return left;
    }

    /**
     * 获得放下count个指定模版的道具需要多少槽位
     *
     * @param template 道具模版
     * @param count    数量
     * @return 槽位数量
     */
    public int getNeedSlot(ItemTemplate template, final int count) {
        System.out.println(template.getId());
        int canOverlapCount = getCanOverlapCount(template.getId());
        return count <= canOverlapCount ? 0 :
                (count - canOverlapCount + template.getMaxOverlap() - 1) / template.getMaxOverlap();
    }

    /**
     * 获得背包中还可以添加的指定道具的个数
     *
     * @param template 道具模版
     * @return 道具个数
     */
    public int getMaxCanAdd(ItemTemplate template) {
        int count = 0;
        final int overlap = template.getMaxOverlap();
        for (Item item : items) {
            if (Item.isEmpty(item)) {
                count += overlap;
            } else if (item.getTemplate() == template) {
                count += (overlap - item.getOverlap());
            }
        }
        return count;
    }

    /**
     * 获得指定的道具模版编号还可以叠加的总数(不考虑空位置)
     *
     * @param templateId 道具模版编号
     * @return 叠加的总数
     */
    private int getCanOverlapCount(int templateId) {
        int left = 0;
        for (Item item : items) {
            if (Item.isEmpty(item)) {
                continue;
            }
            left += (item.getTemplate().getMaxOverlap() - item.getOverlap());
        }
        return left;
    }

    /**
     * @return 空格数量
     */
    public int getEmptySlotCount() {
        int count = 0;
        for (Item item : super.items) {
            if (Item.isEmpty(item)) {
                count ++;
            }
        }
        return count;
    }

    @Override
    public void onLoad() {
        // TODO 未实现
    }

    @Override
    public void onChanged() {
        // TODO 未实现
    }
}